package com.zhuangjie.order.mq.consumer.listener.normal;

import com.zhaungjie.base.conduit.TypeR;
import com.zhaungjie.base.utils.LocalDateTimeOperations;
import com.zhuangjie.base.enums.WechatSubscriptionTemplateId;
import com.zhuangjie.order.entity.Order;
import com.zhuangjie.order.feign.UserFeignService;
import com.zhuangjie.order.mq.producer.structure.OrderMQStructure;
import com.zhuangjie.order.service.OrderService;
import com.zhuangjie.rabbit.listen.wrap.MQListener;
import com.zhuangjie.wx.entity.WechatSubscriptionMessage;
import com.zhuangjie.wx.helper.WxSubscribeMessageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


@Component
@Slf4j
public class OrderRefundMQListener extends MQListener<Long> {


    @Autowired
    private OrderService orderService;

    @Autowired
    private WxSubscribeMessageHelper wxSubMessageHelper;

    @Autowired
    private UserFeignService userFeignService;



    @Override
    public String listenQueue() {
        return OrderMQStructure.Queues.ORDER_REFUND_QUEUE;
    }

    @Override
    public void onMessageArrives(Long orderId) throws Exception {
        log.info("Order监听器/消费者,已接到需要订单退款通知用户订单编号：{}",orderId);
        // 使用order模块进行安全访问
        // moduleSecurityHelper.useModuleSecurityAccess();
        Order order = orderService.getById(orderId);
        if (orderId == null) {
            throw new RuntimeException("获取不到订单中的用户id！");
        }
        String wxOpenId = TypeR.extract(userFeignService.getUserOpenId(order.getUserId()));
        if (wxOpenId == null) return;
        // 构造WechatSubscriptionMessage
        Map<String, String> subscriptionMessageParams = new HashMap<>();
        subscriptionMessageParams.put("character_string1",order.getOrderNo()); //订单编号
        subscriptionMessageParams.put("amount2",String.valueOf(order.getAmount())); //退款金额
        subscriptionMessageParams.put("time3", new LocalDateTimeOperations(LocalDateTime.now()).formatDate("yyyy-MM-dd HH:mm")); //退款时间
        subscriptionMessageParams.put("thing4",order.getRejectionReason() != null?order.getRejectionReason():"用户主动申请"); //退款原因

        try {
            WechatSubscriptionMessage wechatSubscriptionMessage = WechatSubscriptionMessage.builder()
                    .templateId(WechatSubscriptionTemplateId.ORDER_REFUND)
                    .miniProgramPage("pages/index/index")
                    .params(subscriptionMessageParams)
                    .openId(wxOpenId).build();
            wxSubMessageHelper.send(wechatSubscriptionMessage);
        }catch (Exception e){}
    }
}
